<?php


namespace app\community\elasticSearch\lib;


use iflow\swoole\implement\Services\Elasticsearch\Elasticsearch;

class QuerySearch
{
    public Elasticsearch $elasticsearch;
    protected string $indexName;
    protected string $typeName;

    // 查询后的数据
    protected mixed $items = null;
    // 实际需要数据
    protected array $rows = [];
    protected int $last_page = 0;
    protected int $total = 0;

    public function __construct(
        string|array $config
    ) {
        $this->elasticsearch = new Elasticsearch($config);
    }

    /**
     * 执行查询
     * @param buildQueryParams $buildQueryParams
     * @return QuerySearch
     */
    public function query(buildQueryParams $buildQueryParams): static
    {
        $this->items = $this->elasticsearch -> docs()
            -> setDocQuery(
                $buildQueryParams -> getQueryParams()
            )
            -> searchDoc(
                $this->indexName, $this->typeName
            );
        if (is_array($this->items)) {
            $this->last_page = intval($this->items['hits']['total']['value'] / $buildQueryParams -> getQueryParams()['size']);
            $this->total = $this->items['hits']['total']['value'];

            foreach ($this->items['hits']['hits'] as $key => $value){
                $field = [
                    $value['_source']['group_name']
                ];

                $highlight = $buildQueryParams -> getQueryParams()['highlight']??[];

                // 获取高亮数据
                array_walk($highlight['fields'], function ($val, $fieldName) use (&$field, $value) {
                    $field[] = $value['highlight'][$fieldName][0];
                });

                $value['_source']['group_name'] = $field;
                $this->rows[] = $value['_source'];
            }
        }
        return $this;
    }

    /**
     * @param string $indexName
     * @return QuerySearch
     */
    public function setIndexName(string $indexName): static
    {
        $this->indexName = $indexName;
        return $this;
    }

    /**
     * @param string $typeName
     * @return QuerySearch
     */
    public function setTypeName(string $typeName): static
    {
        $this->typeName = $typeName;
        return $this;
    }

    /**
     * @return int
     */
    public function getTotal(): int
    {
        return $this->total;
    }

    /**
     * @return array
     */
    public function getRows(): array
    {
        return $this->rows;
    }

    /**
     * @return mixed
     */
    public function getItems(): mixed
    {
        return $this->items;
    }

    /**
     * @return int
     */
    public function getLastPage(): int
    {
        return $this->last_page;
    }
}
